from flask import Blueprint, Flask, Response, request
from flask import render_template
from get_worldmap_data import CountryStatsDAO
from getYearLine import YearLineDAO
from movie_type_dao import MovieTypeDAO 
from rating_dao import RatingDAO
from word_cloud_dao import WordCloudDAO
from filmReel_dao import FilmReelDAO
from flask import jsonify
import datetime
import pytz
import logging
import requests


app = Flask(__name__)
get_worldmap_data = CountryStatsDAO()
getYearLine = YearLineDAO()

gmovie_type_dao = MovieTypeDAO()
rating_dao = RatingDAO()
word_cloud_dao=WordCloudDAO()

FilmReel_dao=FilmReelDAO()

app.config['JSON_AS_ASCII'] = False
app.json.ensure_ascii = False

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/worldmap')
def get_worldmap():
    data = get_worldmap_data.get_country_stats()
    return jsonify({
        "code":200,
        "message":"success",
        "data":data
    })

@app.route('/api/yearLine')
def yearLine():
    data = getYearLine.get_year_distribution()
    return jsonify({
        "code":200,
        "message":"success",
        "data":data
    })

@app.route('/api/time')
def get_time():
    tz=pytz.timezone('Asia/Shanghai')
    current_time = datetime.datetime.now(tz)
    time_str = current_time.strftime('%Y-%m-%d %H:%M:%S')
    return jsonify({
        "code":200,
        "message":"success",
        "data":time_str
    })

@app.route('/api/typePie')
def typePie():
    data = gmovie_type_dao.get_movie_type_distribution()
    return jsonify({
        "code":200,
        "message":"success",
        "data":data
    })

@app.route('/api/rating/distribution')
def distribution():
    data = rating_dao.get_rating_distribution()
    return jsonify({
        "code": 200,
        "message": "success",
        "data": data
    })

@app.route('/api/wordCloud')
def wordCloud():
    data = word_cloud_dao.get_word_cloud_data()
    return jsonify({
        "code": 200,
        "message": "success",
        "data": data
    })

@app.route('/api/top50movies')
def top50movies():
    data = FilmReel_dao.get_film()
    return jsonify({
        "code": 200,
        "message": "success",
        "data": data
    })

# 定义图片代理API路由
@app.route('/api/proxy-image')
# 图片代理接口，用于解决跨域访问豆瓣图片的问题
def proxy_image():
    image_url = request.args.get('url')  # 从请求参数中获取原始图片URL
    if not image_url:  # 如果URL参数为空
        return 'Missing URL parameter', 400  # 返回400错误
    try:
        # 设置请求头，模拟浏览器访问
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',  # 浏览器标识
            'Referer': 'https://movie.douban.com/'  # 引用页面
        }
        # 发送请求获取图片
        response = requests.get(image_url, headers=headers, stream=True)  # 使用流式请求获取图片
        # 检查响应状态
        if response.status_code == 200:  # 如果请求成功
            # 返回图片数据流
            return Response(
                response.iter_content(chunk_size=1024),  # 分块返回图片数据
                content_type=response.headers['content-type']  # 保持原始内容类型
            )
        else:  # 如果请求失败
            return 'Failed to fetch image', response.status_code  # 返回错误信息
    except Exception as e:  # 捕获所有可能的异常
        return str(e), 500  # 返回500错误


if __name__ == '__main__':
    app.run(debug=True)